package com.example.weather

import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.weather.weather.Forecast
import com.example.weather.weather.Weather
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MainActivity2 : AppCompatActivity() {

    val baseURL = "http://t.weather.itboy.net/api/weather/city/"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)

        val listView = findViewById<android.widget.ListView>(R.id.listView)
        val textView_city: TextView = findViewById(R.id.textView_city)
        val textView_prov: TextView = findViewById(R.id.textView_prov)
        val textView_humi: TextView = findViewById(R.id.textView_humi)
        val textView_temp: TextView = findViewById(R.id.textView_temp)
        val imageView: ImageView = findViewById(R.id.imageView)

        val cityCode = intent.getStringExtra("city_code")
        Log.d("MainActivity2", "City code: $cityCode")

        val queue = Volley.newRequestQueue(this)

        val stringRequest = StringRequest(baseURL + cityCode, { response ->
            Log.d("MainActivity2", "Response: $response")

            val gson = Gson()
            val WeatherType = object : TypeToken<Weather>() {}.type
            val weather: Weather = gson.fromJson(response, WeatherType)

            Log.d("MainActivity2", "Parsed weather: $weather")

            textView_city.text = weather.cityInfo.city
            textView_prov.text = weather.cityInfo.parent
            textView_humi.text = weather.data.shidu
            textView_temp.text = weather.data.wendu

            val firstDay = weather.data.forecast.first()
            when (firstDay.type) {
                "晴" -> imageView.setImageResource(R.drawable.sun)
                "阴" -> imageView.setImageResource(R.drawable.cloud)
                "多云" -> imageView.setImageResource(R.drawable.mcloud)
                "阵雨" -> imageView.setImageResource(R.drawable.rain)
                else -> imageView.setImageResource(R.drawable.thunder)
            }

            val adapter = ArrayAdapter<Forecast>(this, android.R.layout.simple_list_item_1, weather.data.forecast)
            listView.adapter = adapter

            Log.d("MainActivity2", "Weather data displayed on UI")
        }, { error ->
            Log.d("MainActivity2", "Error: $error")
        })
        queue.add(stringRequest)
    }
}